package main

import (
	"github.com/gin-gonic/gin"
)

// r *WantRouter IRouter
type WantRouter struct{}

func (wr *WantRouter) path() string {
	return "/want"
}

func (wr *WantRouter) get() string {
	return wr.path() + "/:id"
}

func (wr *WantRouter) post() string {
	return wr.path()
}

func (wr *WantRouter) put() string {
	return wr.path() + "/:id"
}
func (wr *WantRouter) delete() string {
	return wr.path() + "/:id"
}

func (r *WantRouter) Find(c *gin.Context) {
	c.Param("id")
	wants := NewWants()
	c.JSON(200, &wants)
}

func (r *WantRouter) Create(c *gin.Context) {
	var want Want

	err := c.BindJSON(&want)
	if err != nil {
		done(c, 500, err.Error())
		return
	}

	err = SqliteDB().Create(&want).Error
	if err != nil {
		done(c, 500, err.Error())
		return
	}

	var answers = want.Answers
	for i := 0; i < len(answers); i++ {
		answers[i].WantID = want.ID
	}
	SqliteDB().Create(&answers)
	done(c, 200, &want)
}

func (r *WantRouter) Delete(c *gin.Context) {
	id := c.Param("id")

	var want Want
	err := SqliteDB().Where("id = ?", id).First(&want).Error
	if err != nil {
		done(c, 500, err.Error())
		return
	}

	if err := SqliteDB().Delete(&want).Error; err != nil {
		done(c, 500, err.Error())
		return
	}
	done(c, 200, &want)
}

func (r *WantRouter) Update(c *gin.Context) {
	id := c.Param("id")

	var want Want
	err := SqliteDB().Where("id = ?", id).First(&want).Error
	if err != nil {
		done(c, 500, err.Error())
		return
	}

	c.BindJSON(&want)
	if err := SqliteDB().Where("id = ?", id).Updates(&want).Error; err != nil {
		done(c, 500, err.Error())
		return
	}

	done(c, 200, &want)
}
